<template>
  <div class="code-layout">
    <!-- <div class="code-materials">
      <div>
        <plug-state :statusStr="status" />
        <br />
      </div>
      <div>
        <dl class="code-dl" v-for="(e, i) in detailData.tcp_port_list" :key="i">
          <li v-if="e.endpoint">
            <span class="key">端口{{ e.containerPort }}:</span>
            <span class="val"> {{ e.endpoint }}</span>
          </li>
        </dl>
      </div>
      <div class="file">
        <s3-file-list :s3_access_id="detailDataNow.s3_access_id" :s3_path="detailDataNow.s3_path"
          v-if="detailDataNow.s3_access_id" />
        <file-list :biz_id="$route.query.id" type="workspace" v-else />
      </div>
      <md-preview :biz_id="$route.query.id" type="workspace" class="preview" />
    </div> -->

    <div class="code-info">
      <div class="code-info-item">
        <h3 class="info-title">基本信息<i class="el-icon-edit-outline edit" @click="updateBase" /></h3>
        <ul class="info-item">
          <li>
            <span class="key">名称:</span>
            <span class="val">{{ detailDataNow.name }}</span>
          </li>
          <li>
            <span class="key"> 创建人： </span>
            <span class="val">{{
              detailDataNow.create_user && (detailDataNow.create_user.nick_name ||
                detailDataNow.create_user.username)
            }}</span>
          </li>
          <li>
            <span class="key">创建时间： </span>
            <span class="val">{{ detailDataNow.create_time }}</span>
          </li>
        </ul>
      </div>

      
      <div class="code-info-item">
        <h3 class="info-title">开发环境<i class="el-icon-edit-outline edit" @click="updateEnv" /></h3>
        <dl class="code-dl" v-for="(e, i) in detailDataNow.node_group_list" :key="i">
          <ul class="info-item">
            <li>
              <span class="key">节点类型:</span>
              <span class="val">{{ nodeTypeMaps[e.type] }}</span>
            </li>
            <li>
              <span class="key">资源组:</span>
              <span class="val">{{ e.product.name }}</span>
            </li>
            <li>
              <span class="key">镜像:</span>
              <span class="val">{{ e.image.name }}</span>
            </li>
            <li>
              <span class="key">数量:</span>
              <span class="val">{{ e.pod_num }}</span>
            </li>
          </ul>
        </dl>
      </div>


      <div class="code-info-item">
        <h3 class="info-title">数据集<i class="el-icon-edit-outline edit" @click="updateDataset" /></h3>
        <ul class="info-item">
          <dl class="code-dl" v-for="(e, i) in detailDataNow.dataset_list" :key="i">
            <li>
              <span class="key">名称:</span>
              <span class="val">{{ e.dataset.name }}</span>
            </li>
            <li>
              <span class="key">挂载地址:</span>
              <span class="val">/dataset/{{ e.dataset.alias }}</span>
            </li>
          </dl>
        </ul>
      </div>
      <div class="code-info-item">
        <h3 class="info-title">预训练模型<i class="el-icon-edit-outline edit" @click="updateModel" /></h3>
        <ul class="info-item">
          <dl class="code-dl" v-for="(e, i) in detailDataNow.model_list" :key="i">
            <li>
              <span class="key">名称:</span>
              <span class="val">{{ e.model.name }}</span>
            </li>
            <li>
              <span class="key">版本：</span>
              <span class="val">{{ e.model_version.version }}</span>
            </li>
            <li>
              <span class="key">挂载地址:</span>
              <span class="val">/model/{{ e.model.alias }}</span>
            </li>
          </dl>
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title" v-if="s3_flag">S3输入<i class="el-icon-edit-outline edit" @click="updateInS3" /></h3>
        <ul class="info-item" v-if="s3_flag">
          <dl class="code-dl" v-for="(e, i) in in_s3_list" :key="i">
            <li>
              <span class="key">名称:</span>
              <span class="val">{{ e.s3_name }}</span>
            </li>
            <li>
              <span class="key">桶:</span>
              <span class="val">{{ s3idFormat(e.s3_id) }}</span>
            </li>
            <li>
              <span class="key">路径:</span>
              <span class="val">{{ e.path }}</span>
            </li>
            <li>
              <span class="key">挂载地址:</span>
              <span class="val">/input/{{ e.s3_name }}</span>
            </li>
          </dl>
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title" v-if="s3_flag">S3输出<i class="el-icon-edit-outline edit" @click="updateOutS3" /></h3>
        <ul class="info-item" v-if="s3_flag">
          <dl class="code-dl" v-for="(e, i) in out_s3_list" :key="i">
            <li>
              <span class="key">名称:</span>
              <span class="val">{{ e.s3_name }}</span>
            </li>
            <li>
              <span class="key">桶:</span>
              <span class="val">{{ s3idFormat(e.s3_id) }}</span>
            </li>
            <li>
              <span class="key">路径:</span>
              <span class="val">{{ e.path }}</span>
            </li>
            <li>
              <span class="key">挂载地址:</span>
              <span class="val">/output/{{ e.s3_name }}</span>
            </li>
          </dl>
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title">端口<i class="el-icon-edit-outline edit" @click="updatePort" /></h3>
        <ul class="info-item">
          <dl class="code-dl" v-for="(e, i) in detailDataNow.port_list" :key="i">
            <!-- <li>
              <span class="key">协议:</span>
              <span class="val">{{ e.protocol }}</span>
            </li> -->
            <li>
              <span class="key">端口:</span>
              <span class="val">{{ e.port }}</span>
            </li>
          </dl>
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title">节点信息</h3>
        <dl class="code-dl" v-for="(tag, i) in detailData.tcp_port_list" :key="i">
          <ul class="info-item-tcp-port">
            <li>
              <span class="key">协议：{{ tag.proxyProtocol }}</span>
              <span class="key">容器端口：{{ tag.containerPort }}</span>
              <span class="key">映射端口：{{ tag.nodePort }}</span>
              <span class="key">映射地址：{{ tag.endpoint }}</span>
            </li>
          </ul>
        </dl>
      </div>

      <div class="code-info-item">
        <h3 class="info-title">节点容器信息</h3>
        <div class="info-item"><span>业务节点:</span></div>
        <dl class="code-dl" v-for="(tag, i) in detailData.node_group_list" :key="i">
          <ul class="info-item-tcp-port">
            <li>
              <p class="key">节点分组-{{ i }}</p>
              <div v-for="(pod, j) in tag.pod_list" :key="j">
                <p class="key">节点名称：{{ pod.name }}</p>
                <p class="val">节点id：{{ pod.uid }}</p>
                <p class="val">节点ip：{{ pod.pod_ip }}</p>
                <p class="val">进程数量：500</p>
                <br />
              </div>
            </li>
          </ul>
        </dl>
      </div>

      <div class="code-md">
        <md-preview :biz_id="$route.query.id" type="workspace" class="preview" />
      </div>
    </div>

    <DialogBox title="模型开发基本信息" :visible="showUpdateBaseDialog" :confirm="commitBase" :close="cancelBase">
      <el-form class="form myself-form" ref="form" :rules="baseSubmitRules" :model="addForm" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="配图">
          <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="addForm.avatar" @avatarPath="avatarPath" />
        </el-form-item>
        <el-form-item label="" prop="tensorboard">
          <el-checkbox v-model="addForm.tensorboard">tensorboard</el-checkbox>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="addForm.desc" />
        </el-form-item>
      </el-form>
    </DialogBox>

    <DialogBox title="开发环境基本信息" :visible="showEnvDialog" :confirm="commitEnv" :close="cancelEnv">
      <el-form class="form myself-form" ref="envForm" :rules="submitEnvRules" :model="detailDataNow" label-width="100px">
        <div class="node-module">
          <h3 class="node-module-title">主节点</h3>
          <el-form-item label="环境" prop="mainNodeImageId">
            <el-cascader v-model="mainNode.image_group" :options="imageOptions" :show-all-levels="false"
              class="full-extent-select"></el-cascader>
          </el-form-item>
          <el-form-item label="资源组" prop="mainProduct">
            <el-select v-model="mainNode.product_id" prop="main_product" class="full-extent-select">
              <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="right-btn-box" v-if="slaveNodeList.length == 0">
            <span class="outin-handle">
              <a href="javascript:;" @click="addSlaveNode()">增加</a>
            </span>
          </div>
        </div>
        <div v-for="(tag, i) in slaveNodeList" :key="i">
          <div class="node-module">
            <h3 class="node-module-title">从节点</h3>
            <el-form-item label="环境" prop="slaveImage">
              <el-cascader v-model="tag.image_group" :options="imageOptions" :show-all-levels="false"
                class="full-extent-select"></el-cascader>
            </el-form-item>
            <el-form-item label="资源组">
              <el-select v-model="tag.product_id" class="full-extent-select">
                <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量">
              <el-input-number v-model="tag.pod_num"></el-input-number>
            </el-form-item>
            <div class="right-btn-box">
              <span class="outin-handle">
                <a href="javascript:;" @click="delSlaveNode(i)">删除</a>
                <a href="javascript:;" @click="addSlaveNode()" v-if="i == slaveNodeList.length - 1">增加</a>
              </span>
            </div>
          </div>
        </div>
      </el-form>
    </DialogBox>

    <DialogBox title="数据集" :visible="showDataSetDialog" :confirm="commitDataset" :close="cancelDataset">
      <el-form class="form myself-form" ref="datasetForm" :model="detailDataNow">
        <el-form-item label="数据集">
          <plug-dataset :dataset_list="detailDataNow.dataset_list" @infoDataset="infoDataset"
            v-if="detailDataNow.dataset_list" />
        </el-form-item>
      </el-form>
    </DialogBox>

    <DialogBox title="预训练模型" :visible="showModelDialog" :confirm="commitModel" :close="cancelModel">
      <el-form class="form myself-form" ref="modelForm" :model="detailDataNow">
        <el-form-item label="预训练模型">
          <plug-model :model_list="detailDataNow.model_list" @infoModel="infoModel" v-if="detailDataNow.model_list" />
        </el-form-item>
      </el-form>
    </DialogBox>

    <!-- S3输入 -->
    <el-form class="form myself-form" ref="inS3Form" :model="detailDataNow" v-if="showInS3Dialog">
      <plug-update-s3 ref="plugInS3" :s3_list="in_s3_list" :type="0" :showS3Dialog="showInS3Dialog" @infoS3="commitInS3"
        @onClose="closeInS3Dialog" v-if="in_s3_list" />
    </el-form>

    <el-form class="form myself-form" ref="outS3Form" :model="detailDataNow" v-if="showOutS3Dialog">
      <plug-update-s3 ref="plugOutS3" :s3_list="out_s3_list" :showS3Dialog="showOutS3Dialog" :type="1"
        @infoS3="commitOutS3" @onClose="closeOutS3Dialog" v-if="out_s3_list" />
    </el-form>

    <DialogBox title="端口基本信息" :visible="showPortDialog" :confirm="commitPort" :close="cancelPort">
      <el-form class="form myself-form" ref="portForm" :model="detailDataNow">

        <plug-update-port :port_list="detailDataNow.port_list" @infoPort="infoPort" @onClose="cancelPort"
          v-if="detailDataNow.port_list" />
      </el-form>
    </DialogBox>
  </div>
</template>

<script>
// import plugState from '@/components/module/plug-state'
import plugDataset from '@/components/module/plug-in-dataset'
import plugUpdateS3 from '@/components/module/plug-update-s3'
import plugModel from '@/components/module/plug-in-model'
import plugUpdatePort from '@/components/module/plug-update-port'
import DialogBox from '@/components/module/dialog-box.vue';
import { getExperimentDetail, putExperiment } from '@/api/notebook'
import { getAllProducts } from '@/api/product'
import { getAllImageGroups, getImageDetail } from '@/api/image'
import { getAllAssetS3 } from '@/api/inout'
import { paramMap } from '@/utils/maps'
import { mainImageRule, mainProductRule, slaveImageRule } from '@/utils/rule'
export default {
  data() {
    return {
      s3_flag: paramMap['s3_flag'],
      detailDataNow: {},
      showEnvDialog: false,
      showDataSetDialog: false,
      showModelDialog: false,
      showInS3Dialog: false,
      showOutS3Dialog: false,
      showPortDialog: false,
      imageOptions: [],
      productOptions: [],
      mainNode: { pod_num: 1, type: 0 },
      slaveNodeList: [],
      dataset_list: [],
      in_s3_list: [],
      model_list: [],
      out_s3_list: [],
      port_list: [],
      s3Options: [],
      status: null,
      submitEnvRules: {
        main_image_id: [
          { required: true, message: "该项为必填项" },
        ],
        main_product: [
          { required: true, message: "该项为必填项" },
        ],
        mainNodeImageId: [
          { required: true, validator: mainImageRule.bind(this, this), trigger: 'change' }
        ],
        mainProduct: [
          { required: true, validator: mainProductRule.bind(this, this), trigger: 'change' }
        ],
        tagImageId: [
          { required: true, validator: slaveImageRule.bind(this, this), trigger: 'change' }
        ],
      },
      showUpdateBaseDialog: false,
      addForm: {},
      baseSubmitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到40个字符" },
        ],
      },
    };
  },
  components: {
    plugDataset,
    plugUpdateS3,
    plugModel,
    plugUpdatePort,
    // plugState,
    DialogBox,
  },
  props: ['detailData'],
  watch: {
    detailData(val) {
      this.detailDataNow = JSON.parse(JSON.stringify(val))
      this.getAddForm(this.detailDataNow)
      this.status = this.detailDataNow.status
    }
  },
  async mounted() {
    console.log("mounted", this.detailData)
    this.getS3s()
    this.detailDataNow = JSON.parse(JSON.stringify(this.detailData))
    this.getAddForm(this.detailDataNow)
    this.getAllImageGroups()
    this.getProductList()
  },
  destroyed() {

  },
  methods: {
    updateBase() {
      this.showUpdateBaseDialog = true
      this.addForm = { ...this.detailDataNow }
    },

    commitBase() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await putExperiment(this.addForm);
          if (res && res.data) {
            this.$emit("getDetail")
            this.showUpdateBaseDialog = false
          }
        }
      })
    },
    cancelBase() {
      this.showUpdateBaseDialog = false
    },
    avatarPath(data) {
      this.addForm.avatar = data;
    },
    s3idFormat(s3_id) {
      for (let s3 of this.s3Options) {
        if (s3_id?.toString() == s3.id) {
          return s3.name
        }
      }
      return s3_id
    },
    async getS3s() {
      let res = await getAllAssetS3({});
      this.s3Options = res.data
    },
    toEdte(property) {
      this[property].showInput = true
      this[property] = JSON.parse(JSON.stringify(this[property]))
    },
    lookLog(row) {
      console.log(row)
    },
    formatterRole(type) {
      let role = {
        '1': '主节点',
        '2': '从节点'
      }
      return role[type]
    },
    async getAddForm(data) {
      this.slaveNodeList = []
      this.in_s3_list = []
      this.out_s3_list = []
      for (let node of data.node_group_list) {
        if (node.type == 1) {
          this.mainNode = node
          let res = await getImageDetail({ id: this.mainNode.image_id })
          let mainImage = res.data
          this.mainNode.image_group = [mainImage.visibility.toString(), mainImage.engine.toString(), mainImage.id]
        } else {
          let res = await getImageDetail({ id: node.image_id })
          let slaveImage = res.data
          let slaveNode = node
          slaveNode.image_group = [slaveImage.visibility.toString(), slaveImage.engine.toString(), slaveImage.id]
          this.slaveNodeList.push(slaveNode)
        }
      }
      console.log(data, "data");
      if (data.s3_list.length > 0) {
        for (let s3 of data.s3_list) {
          if (s3.type == 0) {
            this.in_s3_list.push(s3)
          }
          else {
            this.out_s3_list.push(s3)
          }
        }
        console.log("out_s3_list", this.out_s3_list)
        console.log("in_s3_list", this.in_s3_list)
      }
    },
    updateEnv() {
      this.showEnvDialog = true
    },
    commitEnv() {
      this.detailDataNow.node_group_list = []
      this.mainNode.type = 1
      this.mainNode.image_id = this.mainNode.image_group[2]
      this.detailDataNow.node_group_list.push(this.mainNode)
      for (let i = 0; i < this.slaveNodeList.length; i++) {
        this.slaveNodeList[i].type = 2
        this.slaveNodeList[i].image_id = this.slaveNodeList[i].image_group[2]
        this.detailDataNow.node_group_list.push(this.slaveNodeList[i])
      }
      this.$refs.envForm.validate(async (valid) => {
        if (valid) {
          let res = await putExperiment(this.detailDataNow);
          if (res && res.data) {
            this.showEnvDialog = false
            this.freshData()
          }
        }
      })
    },
    closePortDialog() {
      this.showPortDialog = false
    },
    cancelEnv() {
      this.showEnvDialog = false
    },
    addSlaveNode() {
      let data = { type: 1, pod_num: 1 }
      this.slaveNodeList.push(data)
    },
    delSlaveNode(i) {
      this.slaveNodeList.splice(i, 1)
    },
    async getAllImageGroups() {
      let res = await getAllImageGroups()
      this.imageOptions = res.data
    },
    updatePort() {
      this.showPortDialog = true
    },
    async commitPort() {
      console.log(this.detailDataNow, "this.detail");
      let res = await putExperiment(this.detailDataNow);
      if (res && res.data) {
        this.showPortDialog = false
        this.freshData()
      }
    },
    cancelPort() {
      this.showPortDialog = false
    },
    infoPort(ports) {
      console.log("Ports", ports)
      this.detailDataNow.port_list = ports
      this.commitPort()
    },
    updateDataset() {
      this.showDataSetDialog = true
      console.log("showDataSetDialog2", this.showDataSetDialog)
    },
    async commitDataset() {
      let res = await putExperiment(this.detailDataNow);
      console.log("res", res)
      if (res && res.data) {
        this.showDataSetDialog = false
        console.log("showDataSetDialog", this.showDataSetDialog)
        this.freshData()
      }
    },
    cancelDataset() {
      this.showDataSetDialog = false
    },
    infoDataset(datasets) {
      datasets.forEach(e => {
        e.dataset_id = e.id
        e.dataset = {
          name: e.name,
          alias: e.alias,
          id: e.id
        }
      })
      this.detailDataNow.dataset_list = datasets
      // console.log("dataset", this.detailDataNow.dataset_list)
    },

    updateModel() {
      this.showModelDialog = true
    },
    async commitModel() {
      let res = await putExperiment(this.detailDataNow);
      if (res && res.data) {
        console.log("begin fresh")
        this.freshData()
        this.showModelDialog = false
      }
    },
    cancelModel() {
      this.showModelDialog = false
    },
    infoModel(models) {
      this.detailDataNow.model_list = models
      console.log('111111111111111111111',models);
    },

    updateInS3() {
      this.getAddForm(this.detailDataNow)
      this.showInS3Dialog = true
    },
    async getProductList() {
      let res = await getAllProducts()
      this.productOptions = res.data
    },
    async commitInS3(s3_list) {
      this.detailDataNow.s3_list = []

      try {
        this.in_s3_list = s3_list.filter(item => Object.keys(item).length !== 0)
        for (let i = 0; i < s3_list.length; i++) {
          s3_list[i].type = 0
          this.detailDataNow.s3_list.push(this.in_s3_list[i])
        }

        this.out_s3_list = this.out_s3_list.filter(item => Object.keys(item).length !== 0)
        for (let i = 0; i < this.out_s3_list.length; i++) {
          this.out_s3_list[i].type = 1
          this.detailDataNow.s3_list.push(this.out_s3_list[i])
        }

        let res = await putExperiment(this.detailDataNow);
        if (res && res.data) {
          this.getAddForm(this.detailDataNow)
          this.showInS3Dialog = false
          // this.freshData()
        }
      } catch (error) {
        console.log(error);
      }
    },
    closeInS3Dialog() {
      this.getAddForm(this.detailDataNow)
      this.showInS3Dialog = false
    },
    infoInS3(s3s) {
      this.closeInS3Dialog()
      console.log("in s333", s3s)
      this.in_s3_list = s3s
      this.commitInS3()
    },
    closeOutS3Dialog() {
      this.getAddForm(this.detailDataNow)
      this.showOutS3Dialog = false
    },
    updateOutS3() {
      this.getAddForm(this.detailDataNow)
      this.showOutS3Dialog = true
    },
    async commitOutS3(s3_list) {
      this.detailDataNow.s3_list = []
      try {
        this.in_s3_list = this.in_s3_list.filter(item => Object.keys(item).length !== 0)
        for (let i = 0; i < this.in_s3_list.length; i++) {
          this.in_s3_list[i].type = 0
          this.detailDataNow.s3_list.push(this.in_s3_list[i])
        }

        this.out_s3_list = s3_list.filter(item => Object.keys(item).length !== 0)
        for (let i = 0; i < s3_list.length; i++) {
          s3_list[i].type = 1
          this.detailDataNow.s3_list.push(this.out_s3_list[i])
        }

        let res = await putExperiment(this.detailDataNow);
        if (res && res.data) {
          this.showOutS3Dialog = false
          this.getAddForm(this.detailDataNow)
          // this.freshData()
        }
      } catch (error) {
        console.log(error);
      }
    },

    infoOutS3(s3s) {
      this.closeOutS3Dialog()
      this.out_s3_list = s3s
      this.commitOutS3()
    },
    async freshData() {
      let res = await getExperimentDetail({ id: this.detailData.id });
      console.log(res, "res");
      if (res && res.data) {
        console.log("fresh", res.data)
        this.$emit('update:detailData', res.data)
      }
    }

  }
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/code.less";
</style>
